package com.hyh.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyh.admin.domain.resources.ResourcesRating;
import com.hyh.admin.mapper.resources.ResourcesRatingMapper;
import com.hyh.admin.service.IResourcesRatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/*
 *  资源评分-实现类
 */
@Service
public class ResourcesRatingServiceImpl implements IResourcesRatingService {

    @Autowired
    private ResourcesRatingMapper resourcesRatingMapper;
    @Override
    public int insertResourcesRating(ResourcesRating resourcesRating) {
        return resourcesRatingMapper.insert(resourcesRating);
    }

    @Override
    public String selectResourcesRatingAvg(Long resourcesId) {
        double sum = 0;
        LambdaQueryWrapper<ResourcesRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ResourcesRating::getResourcesId, resourcesId);
        List<ResourcesRating> ratings = resourcesRatingMapper.selectList(queryWrapper);

        // 在计算时检查score是否是合法的数字
        for (ResourcesRating resourcesRating : ratings) {
            String score = resourcesRating.getScore();
            if (score != null) {
                try {
                    sum += Double.parseDouble(score);
                } catch (NumberFormatException e) {
                    // 如果不是有效数字，可以选择忽略或记录错误
                    throw new IllegalArgumentException("无效的评分值: " + score);
                }
            }
        }

        // 计算平均值时，避免除以0
        double average = !ratings.isEmpty() ? sum / ratings.size() : 0;
        return String.valueOf(average);

    }

    @Override
    public String selectMyResourcesRating(Long resourcesId, Long userId) {
        LambdaQueryWrapper<ResourcesRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ResourcesRating::getResourcesId, resourcesId);
        queryWrapper.eq(ResourcesRating::getUserId, userId);
        ResourcesRating resourcesRating = resourcesRatingMapper.selectOne(queryWrapper);
        if (resourcesRating != null) {
            return resourcesRating.getScore();
        }
        return null;
    }
}
